<%= stylesheet_link_tag "fullscreen_play/_index" %>

<% if Rails.env.development? %>
  <style>
      #wrapper {
          background-color: lightpink;
      }
  </style>
<% end %>

<%= javascript_include_tag 'countUp.min' %>

<script type="text/javascript" charset="utf-8">
    var STBType = Authentication.CTCGetConfig("STBType"); // 机顶盒型号

    if (STBType === "EC6108V8") {
        setInterval(function () {
            window.focus();
        }, 500);
    }

    // 扩展jQuery
    $.fn.showLong = function () {
        this.finish().show();
        return this;
    };

    $.fn.shine = function (options) {
        // 合并默认值和用户设定值:
        var opts = $.extend({}, $.fn.shine.defaults, options);
        this.stop().show(opts.fade_duration).delay(opts.delay_duration).hide(opts.fade_duration);
        return this;
    };

    // 设定默认值:
    $.fn.shine.defaults = {
        fade_duration: 0,
        delay_duration: 5000
    };

    var interval; // 定时循环对象, 用作清除用

    var songInfo, //左上角的歌曲信息
        firstMarquee, // 第一首歌曲走马灯
        secondMarquee, // 第二首歌曲走马灯
        counter, // 计时器实例
        control, //控制选单
        favBtn, // 收藏按钮
        playBtn, // 播放按钮
        jq_list, // 歌单列表 jquery 实例
        fe_list, // 歌单列表 焦点框架 实例
        firstSong, // 第一首歌, 用作给iframe初始化, 滚动歌曲信息需要
        secondSong, // 第二首歌, 滚动歌曲信息需要
        divStart, // 已播放时长div
        divDuration, // 持续时间div
        offset, // 进度条偏移量
        barLeft, // 已播放进度条
        divVolume, // 音量显示
        divSpeed; // 速度显示

    var frame, // iframe窗体
        mp, // 播放器实例
        isMuted, // 是否被静音, true => 已被静音, false => 非静音
        volume = 100, // 音量
        speed = 1, //播放速度, 初始为1
        isPaused = false, // 是否被暂停, true => 已被暂停, false => 正在播放
        startTime = 0, // 已播放时长, 默认0
        duration = 300, // 总时长, 默认5分钟
        halfDuration, // 总时长一半, 某些盒子不弹起768, 不能自动切歌, 最后播放和总时长都会变成0
        updateHistoryFlag = true, // 更新歌曲历史的标志位
        virtualEvent; // 虚拟的键盘事件

    bind_method(document, "keydown", function (e) {
        e = e || window.event;
        var keyValue = e.which || e.keyCode;
        switch (keyValue) {
            case 0x0031: // 键盘1, 直接跳转订购
                <% if cookies[:order_type] == 'free' %>
                    window.location.href = "<%= platform_order_path %>" + "?path=" + "<%= request.path %>" + "&id=" + "<%= params[:id] %>" + "&play_type=" + "<%= params[:play_type] %>" + "&second_prev=" + "<%= params[:second_prev] %>" + "&song_id=" + firstSong.data("id");
                <% end %>
            case 65: // 键盘a
            case 259: // 音量+
                volume = volume >= 100 ? 100 : volume + 5;
                divVolume.text(volume).shine();
                isMuted = false;
            <% unless Rails.env.development? %>
                mp.setMuteFlag(0);
                mp.setVolume(volume);
            <% end %>
                break;
            case 83: // 键盘s
            case 260: // 音量-
                volume = volume <= 0 ? 0 : volume - 5;
                divVolume.text(volume).shine();
                isMuted = false;
            <% unless Rails.env.development? %>
                mp.setMuteFlag(0);
                mp.setVolume(volume);
            <% end %>
                break;
            case 68: // 键盘d
            case 261: // 静音
                isMuted = !isMuted;
                if (isMuted) {
                    divVolume.text("静音").showLong();
                    <% unless Rails.env.development? %>
                    mp.setMuteFlag(1);
                    <% end %>
                }
                break;
            case 768:
                // 虚拟事件
                virtualEvent = JSON.parse(Utility.getEvent());
                switch (virtualEvent.type) {
                    case "EVENT_MEDIA_BEGINING":
                        // 当媒体播放器中的媒体播放到起始端时触发
                        // 这个事件没有办法触发, 妈的! 巧板眼! 垃圾!
                        break;
                    case "EVENT_MEDIA_END":
                        // 当媒体播放器中的媒体播放到末端时触发
                        if (startTime > halfDuration) {
                            playNext();
                        }
                        break;
                    case "EVENT_MEDIA_ERROR":
                        // 当媒体播放器，发生异常时触发
                        // 放下一首, 如果一直不行, 会跳转到上一个页面
                        playNext();
                        break;
                }
                break;
        }
    });

    // 计算iframe的src, 华为中兴两平台有不同
    var changeMediaSrc = function (contentID) {
        <% unless Rails.env.development? %>
        var last, host, src;
        var epgDomain = Authentication.CTCGetConfig("EPGDomain");
        <% if cookies[:platform].include?('HUAWEI') %>
        last = epgDomain.indexOf("/", 10);
        host = epgDomain.substr(0, last);
        src = host + "/EPG/MediaService/SmallScreen.jsp?ContentID=" + contentID + "&Left=0&Top=0&Width=1280&Height=720&CycleFlag=0&GetCntFlag=0";
        <% else %>
        last = epgDomain.lastIndexOf("/");
        host = epgDomain.substr(0, last);
        src = host + "/MediaService/SmallScreen?ContentID=" + contentID + "&Left=0&Top=0&Width=1280&Height=720&CycleFlag=0&GetCntFlag=0";
        <% end %>
        $("iframe#one_frame").attr("src", src);
        // setTimeout必须为2秒, 必须为2秒, 必须为2秒,
        // 少于2秒长虹盒子会出现 mp.getCurrentPlayTime()为0的情况
        // 并且要调用暂停和播放, 才能让播放时长正常响应, playFromStart()、gotoStart()依然可能导致异常!!!
        setTimeout(function () {
            window.focus();
            if (STBType === "ITV628-HD") {
                mp.pause();
                mp.resume();
            }
        }, 2000);
        <% end %>

        if (firstSong.attr("data-fav") === "true") {
            favBtn.children(".control_item_icon").removeClass("icon-heart").addClass("icon-heart-green");
            favBtn.children(".control_item_text").text("取消");
        } else {
            favBtn.children(".control_item_icon").removeClass("icon-heart-green").addClass("icon-heart");
            favBtn.children(".control_item_text").text("收藏");
        }
        $.ajax({
            url: "<%= users_song_view_count_increment_path %>" + "?id=" + firstSong.data("id"),
            dataType: "text",
            type: "POST",
        });
    };

    // 重置定时器并跳转到订购
    var resetCount = function () {
        <% if cookies[:order_type] == 'free' %>
        counter.reset();
        counter.start(function () {
            // TODO 直接停掉视频播放，不再做暂停处理，防止有的机顶盒可以绕过事件处理函数直接恢复视频播放
            window.location.href = "<%= platform_order_path %>" + "?path=" + "<%= request.path %>" + "&id=" + "<%= params[:id] %>" + "&play_type=" + "<%= params[:play_type] %>" + "&second_prev=" + "<%= params[:second_prev] %>" + "&song_id=" + firstSong.data("id");
        });
        <% end %>
    };

    // 回到全屏播放之前的页面
    var goBack = function () {
        // https://juejin.cn/post/6844903773622501383#heading-0
        // 深度解密setTimeout和setInterval——为setInterval正名！
        clearInterval(interval);
        setTimeout(function () {
            <% unless Rails.env.development? %>
            mp.stop();
            <% end %>
            var prevPath = Cookies.get('prev')
            var params = Cookies.get(prevPath)

            if (params) {
                window.location.href = prevPath + params
            } else {
                window.location.href = prevPath
            }
        }, 0);
    };

    // 更新播放进度条
    var updateProgress = function () {
        // 某些盒子不能触发768, 并且播放到最末尾会卡住, 最后已播放时间变为0, duration为0, 需要手动切歌; 要与能触发768的盒子做个兼容
        // 某些视频播放到末尾也会变成已播放时间变为0, duration为0; 此时会造成两次切换下一曲, 要做兼容
        interval = setInterval(function () {
            <% unless Rails.env.development? %>
            startTime = mp.getCurrentPlayTime();
            duration = mp.getMediaDuration();
            if (duration > 0) {
                halfDuration = duration / 2;
            }
            <% end %>

            if (startTime > 60) {
                // 更新播放历史
                if (updateHistoryFlag) {
                    $.ajax({
                        url: "<%= users_add_history_path %>" + "?id=" + firstSong.data("id"),
                        dataType: "text",
                        type: "POST",
                    }).always(function () {
                        updateHistoryFlag = false;  // 不管成功与否, 标志位改成false, 这样只推送一次, 逻辑交给后端处理
                    });
                }

                <% if cookies[:order_type] == 'free' %>
                // 非会员过60秒跳转订购
                window.location.href = "<%= platform_order_path %>" + "?path=" + "<%= request.path %>" + "&id=" + "<%= params[:id] %>" + "&play_type=" + "<%= params[:play_type] %>" + "&second_prev=" + "<%= params[:second_prev] %>" + "&song_id=" + firstSong.data("id");
                <% end %>
            }

            if (startTime === 0 && duration === 0 && halfDuration > 0) {
                halfDuration = 0;
                playNext();
            }

            divStart.text(new Date(startTime * 1000).toISOString().substr(14, 5));
            divDuration.text(new Date(duration * 1000).toISOString().substr(14, 5));

            offset = 832 * (startTime / duration); // 52是rem, 16是fontSize
            barLeft.css({"width": offset + "px"});
        }, 1000);
    };

    // 操作播放列表
    var spliceList = function (itemIndex) {
        var list_item = $(".list_item");
        var removeList = $(list_item.splice(0, itemIndex)).remove(); // 被拿掉的列表
        list_item.eq(-1).after(removeList);
        FocusEngine.getWidgetById($(".list_item_text").get(0).id).focus();
    };

    // 切歌函数
    var playNext = function () {
        if ($(".list_item").length === 1) {
            goBack();
        } else {
            updateHistoryFlag = true; // 切歌重新打开更新歌曲标志位
            if (speed !== 1) {
                speed = 1;
                speedAnimation();
            }
            var list_item = $(".list_item");
            var removeList = $(list_item.splice(0, 1)).remove(); // 被拿掉的列表
            list_item.eq(-1).after(removeList);
            list_item = $(".list_item");
            firstSong = list_item.eq(0);
            secondSong = list_item.eq(1);
            firstMarquee.text(firstSong.text());
            secondMarquee.text(secondSong.text());
            changeMediaSrc(firstSong.data("content_id"));
            resetCount();
        }
    };

    var speedAnimation = function () {
        if (speed < 0) {
            divSpeed.text("快退 X " + speed).showLong();
            mp.fastRewind(speed);
        } else if (speed > 1) {
            divSpeed.text("快进 X " + speed).showLong();
            mp.fastForward(speed);
        } else {
            divSpeed.text("").hide();
            mp.resume();
        }
    };

    $(function () {
        // 歌曲信息
        songInfo = root.getWidgetById("song-info");
        // 第一首歌曲走马灯
        firstMarquee = $("#first-marquee");
        // 第二首歌曲走马灯
        secondMarquee = $("#second-marquee");

        <% if cookies[:order_type] == 'free' %>
        // 计时器实例
        counter = new CountUp("count-down-text-number", 0, {
            startVal: 60,
            duration: 60,
            useEasing: false
        });
        <% end %>

        // 控制面板
        control = root.getWidgetById("control");
        // 控制按钮
        favBtn = $("#fav");
        // 播放按钮
        playBtn = $("#play");
        // 歌单列表 jquery 实例
        jq_list = $("#list");
        // 歌单列表 焦点框架 实例
        fe_list = root.getWidgetById("list");
        // 第一首歌
        firstSong = jq_list.find(".list_item").eq(0);
        // 已播放时长div
        divStart = $(".progress_time_start");
        // 持续时间div
        divDuration = $(".progress_time_end");
        // 已播放进度条
        barLeft = $(".progress_bar_left");
        // 音量显示
        divVolume = $("#volume");
        // 速度显示
        divSpeed = $("#speed");

        // iframe窗体
        frame = $("iframe#one_frame");

        // 为 iframe src赋值, 开始播放
        changeMediaSrc(firstSong.data("content_id"));

        <% unless Rails.env.development? %>
        // 等待 iframe 加载完成, 之后进行操作.
        <%= render 'mp.js' %>
        <% end %>

        <% if cookies[:order_type] == 'free' %>
        // 开始计时
        resetCount();
        <% end %>
        updateProgress();

        // 左37 上38 右39 下40
        songInfo.on("keydown", function (e) {
            e = e || window.event;
            var keyValue = e.which || e.keyCode;
            switch (keyValue) {
                case 8:
                case 27:
                    goBack();
                    break;
                case 13:
                case 37:
                case 38:
                case 39:
                case 40:
                    songInfo.disable();
                    control.show();
                    control.enable();
                    control.focus();
            }
        });

        control.on("keydown", function (e) {
            e = e || window.event;
            var keyValue = e.which || e.keyCode;
            switch (keyValue) {
                case 8:
                case 27:
                    // 关闭面板, 回到歌曲信息
                    control.disable();
                    control.hide();
                    songInfo.show();
                    songInfo.enable();
                    songInfo.focus();
                    break;
                case 13:
                    switch (String(e.target.con.dataset.kind)) {
                        case "切歌":
                            playNext();
                            break;
                        case "快退":
                            if (speed > 0) {
                                speed = -2;
                            } else {
                                speed = speed <= -32 ? 1 : speed * 2;
                            }
                            speedAnimation();
                            break;
                        case "快进":
                            if (speed < 0) {
                                speed = 2;
                            } else {
                                speed = speed >= 32 ? 1 : speed * 2;
                            }
                            speedAnimation();
                            break;
                        case "收藏":
                            firstSong = $(".list_item").eq(0);
                            $.ajax({
                                url: "<%= users_toggle_fav_path %>" + "?id=" + firstSong.data("id") + "&force=true",
                                dataType: "text",
                                type: "POST",
                                success: function (data) {
                                    if (data === "create") {
                                        firstSong.attr("data-fav", true);
                                        favBtn.children(".control_item_icon").removeClass("icon-heart").addClass("icon-heart-green");
                                        favBtn.children(".control_item_text").text("取消");
                                    } else {
                                        firstSong.attr("data-fav", false);
                                        favBtn.children(".control_item_icon").removeClass("icon-heart-green").addClass("icon-heart");
                                        favBtn.children(".control_item_text").text("收藏");
                                    }
                                }
                            });
                            break;
                        case "已点":
                            control.disable();
                            fe_list.show();
                            // 聚焦第一首歌, 不然会出现怪异行为
                            fe_list.enable();
                            FocusEngine.getWidgetById($(".list_item_text").get(0).id).focus();
                            break;
                        case "点歌":
                            window.location.href = "<%= recommend_path %>";
                            break;
                        case "重置":
                            if (speed !== 1) {
                                speed = 1;
                                speedAnimation();
                            }
                            isPaused = false;
                            mp.playFromStart();
                            resetCount();
                            break;
                        case "播放":
                            if (speed !== 1) {
                                speed = 1;
                                speedAnimation();
                            }
                            mp.resume();
                            isPaused = !isPaused;
                            if (isPaused) {
                                playBtn.removeClass("icons_pause").addClass("icons_play");
                                mp.pause();
                            } else {
                                playBtn.removeClass("icons_play").addClass("icons_pause");
                                mp.resume();
                            }
                            break;
                    }
                    break;
            }
        });

        fe_list.on("keydown", function (e) {
            e = e || window.event;
            var keyValue = e.which || e.keyCode;
            switch (keyValue) {
                case 8:
                case 27:
                    // 关闭list, 回到面板
                    fe_list.disable();
                    fe_list.hide();
                    control.enable();
                    control.focus();
                    break;
                case 13:
                    var con = e.target.con;
                    var dataset = con.dataset;
                    var ele = $(con).parent(".list_item");
                    var index = $(".list_item").index(ele);
                    firstSong = $(".list_item").eq(0);
                    // 如果是队首不操作
                    if (ele.data("id") !== firstSong.data("id")) {
                        switch (String(dataset.kind)) {
                            case "song":
                                // 如果是队首不操作
                                var list_item = $(".list_item");
                                var removeList = $(list_item.splice(0, index)).remove(); // 被拿掉的列表
                                list_item.eq(-1).after(removeList);
                                FocusEngine.getWidgetById($(".list_item_text").get(0).id).focus();
                                list_item = $(".list_item");
                                firstSong = list_item.eq(0);
                                secondSong = list_item.eq(1);
                                firstMarquee.text(firstSong.text());
                                secondMarquee.text(secondSong.text());
                                changeMediaSrc(firstSong.data("content_id"));
                                resetCount();
                                if (speed !== 1) {
                                    speed = 1;
                                    speedAnimation();
                                }
                                break;
                            case "up":
                                ele.remove();
                                firstSong.after(ele);
                                list_item = $(".list_item");
                                secondSong = list_item.eq(1);
                                secondMarquee.text(secondSong.text());
                                break;
                            case "delete":
                                // 在删除键上操作过快会导致异常, 估计是异步原因, 没有办法, 只能增加使用成本
                                ele.remove();
                                list_item = $(".list_item");
                                FocusEngine.getWidgetById($(".list_item_text").get(index - 1).id).focus();
                                list_item = $(".list_item");
                                if (list_item.length > 1) {
                                    secondSong = list_item.eq(1);
                                    secondMarquee.text(secondSong.text());
                                } else {
                                    secondMarquee.text("没有下一首了");
                                }
                                break;
                        }
                    }
                    break;
            }
        });

        // 歌单列表中的歌曲走马灯效果
        fe_list.on("focus", function (e) {
            var ele = $(e.target.con).find(".marquee-truncate");
        });
        fe_list.on("blur", function (e) {
            var ele = $(e.target.con).find(".marquee-truncate");
        });
    });
</script>

<div id="main">
  <div id="wrapper">
    <% if cookies[:order_type] == 'free' %>
      <div class="count-down">
        <div class="count-down-text">
          免费试听<span id="count-down-text-number"></span>秒
        </div>
      </div>
    <% end %>

    <% if cookies[:order_type] == 'free' %>
        <div id="immediate-order"></div>
    <% end %>

    <div id="song-info" class="song-info" fe-role="Widget" fe-cfg="default_focus:yes,">
      <div class="song-info-first">
        <div class="marquee-truncate overflow-hidden">
          <marquee id="first-marquee">
            <%= "#{@items[0][:name]} - #{@items[0][:redundant_singer_name]}" %>
          </marquee>
        </div>
      </div>
      <div class="song-info_second">
        <div class="marquee-truncate overflow-hidden">
          <span id="second-marquee">
            <% if @items[1] %>
              <%= "#{@items[1][:name]} - #{@items[1][:redundant_singer_name]}" %>
            <% else %>
              没有下一首了
            <% end %>
          </span>
        </div>
      </div>
    </div>

    <div id="control" class="control" fe-role="Switch" fe-cfg="disable:yes,">
      <div data-kind="伴唱" class="control_item">
        <div class="control_item_icon icon-voice-off"></div>
        <div class="control_item_text grey">伴唱</div>
      </div>
      <div data-kind="切歌" class="control_item" fe-role="Widget" fe-index="0" fe-goto="0;1;6;0">
        <div class="control_item_icon icon-go-end"></div>
        <div class="control_item_text">切歌</div>
      </div>
      <div data-kind="快退" class="control_item" fe-role="Widget" fe-index="1" fe-goto="1;2;6;0">
        <div class="control_item_icon icon-double-left"></div>
        <div class="control_item_text">快退</div>
      </div>
      <div data-kind="快进" class="control_item" fe-role="Widget" fe-index="2" fe-goto="2;3;6;1">
        <div class="control_item_icon icon-double-right"></div>
        <div class="control_item_text">快进</div>
      </div>
      <div id="fav"
           data-kind="收藏" class="control_item" fe-role="Widget" fe-index="3" fe-goto="3;4;6;2">
        <div class="control_item_icon icon-heart"></div>
        <div class="control_item_text">收藏</div>
      </div>
      <div data-kind="已点" class="control_item" fe-role="Widget" fe-index="4" fe-goto="4;5;6;3">
        <div class="control_item_icon icon-list-bottom"></div>
        <div class="control_item_text">已点</div>
      </div>
      <div data-kind="点歌" class="control_item" fe-role="Widget" fe-index="5" fe-goto="5;5;6;4">
        <div class="control_item_icon icon-performance"></div>
        <div class="control_item_text">点歌</div>
      </div>

      <div class="icons">
        <div data-kind="重置" class="icons_reset" fe-role="Widget" fe-index="6" fe-goto="2;7;6;6"></div>
        <div id="play" data-kind="播放" class="icons_pause" fe-role="Widget" fe-index="7" fe-goto="3;7;7;6"></div>
      </div>
    </div>

    <div id="list" class="list" fe-role="Scroll" fe-cfg="disable:yes,disable_child_cache:yes,scroll_dir:v,scroll_duration:0.3,scroll_easing:ease-out">

      <div class="scroll-list" style="height: <%= (@items.size+1) * 40 %>px">
        <% @items.each do |item| %>
          <div
            class="list_item"
            data-id="<%= item.id %>"
            data-content_id="<%= item.content_id %>"
            data-fav="<%= item.id.in? @fav_ids %>"
          >
            <div
              class="list_item_text"
              data-kind="song"
              fe-role="Widget">
              <div class="marquee-truncate">
                <span><%= "#{item[:name]} - #{item[:redundant_singer_name]}" %></span>
              </div>
            </div>
            <div data-kind="up" class="list_item_up" fe-role="Widget"></div>
            <div data-kind="delete" class="list_item_delete" fe-role="Widget"></div>
          </div>
        <% end %>
      </div>

    </div>

    <div id="speed"></div>
    <div id="volume"></div>

    <div class="progress">
      <div class="progress_bar">
        <div class="progress_bar_left"></div>
      </div>
      <div class="progress_time">
        <span class="progress_time_start"></span> /
        <span class="progress_time_end"></span>
      </div>
    </div>
  </div>

  <iframe
    id="one_frame"
    src
    width="1280px"
    height="720px"
    name="if_smallscreen"
    frameborder="no"
    scrolling="no"
  ></iframe>
</div>
